 <#import "inc/macro-page.html" as panel>
<#import "macro-filter-card-box.html" as seachpanel>
<#escape x as x?html>
<@panel.header "人才队伍趋势预警" "">
</@panel.header>
<@panel.body>
            <!-- Bread crumb -->
            <div class="row page-titles">
                <div class="col-md-5 align-self-center">
                    <h3>人才队伍趋势预警</h3> </div>
                <div class="col-md-7 align-self-center">
                    <div class="page-nav-bar">
                       <button class="btn btn-info btn-click-bind" data-sign="11">专家人才晋升趋势</button>
                       <button class="btn btn-inverse btn-click-bind" data-sign="12" disabled>职称等级晋升趋势</button>
                       <button class="btn btn-info btn-click-bind" data-sign="13">技能等级晋升趋势</button>
                       <button class="btn btn-info btn-click-bind" data-sign="14">人才信息定向筛选</button>
                    </div> 
                </div>
            </div>
            <!-- End Bread crumb -->
            <!-- Container fluid  -->
            <div class="container-fluid">
                <!-- Start Page Content --> 
                <div class="card">
					<div class="custom-card-header quick-bar">
						<div class="hint">&nbsp;</div>
						<@seachpanel.filterbox></@seachpanel.filterbox>
					    <button id="id-export-file" type="button" class="btn btn-dark btn-outline btn-sm m-l-10" title="导出"><i class="fa fa-share-square-o"></i></button>
					</div>                	
                    <div class="card-body">
		                  <div id="id-diagram-group" class="row m-t-20">
		                  	<div class="col-lg-6 m-b-40">
		                  		<div id="id-chart-01" style="height: 420px"></div>
		                  		
		                             <table id="id-table-01" class="table table-bordered content-center"  cellspacing="0" width="100%">
		                                 <thead>
		                                     <tr>
		                                         <th>&nbsp;</th>
		                                         <th>2023年</th>
		                                         <th>2024年</th>
		                                         <th>2025年</th>
		                                         <th>2026年</th>
		                                         <th>2027年</th>
		                                     </tr>
		                                 </thead>
		                              </table>
		                  	</div>
		                  	<div class="col-lg-6 m-b-40">
		                  		<div id="id-chart-02" style="height: 420px"></div>
		                  		
		                             <table id="id-table-02" class="table table-bordered content-center"  cellspacing="0" width="100%">
		                                 <thead>
		                                     <tr>
		                                         <th>&nbsp;</th>
		                                         <th>2023年</th>
		                                         <th>2024年</th>
		                                         <th>2025年</th>
		                                         <th>2026年</th>
		                                         <th>2027年</th>
		                                     </tr>
		                                 </thead>
		                              </table>
		                  	</div>
		                  	<div class="col-lg-6 m-b-40">
		                  		<div id="id-chart-03" style="height: 420px"></div>
		                             <table id="id-table-03" class="table table-bordered content-center"  cellspacing="0" width="100%">
		                                 <thead>
		                                     <tr>
		                                         <th>&nbsp;</th>
		                                         <th>2023年</th>
		                                         <th>2024年</th>
		                                         <th>2025年</th>
		                                         <th>2026年</th>
		                                         <th>2027年</th>
		                                     </tr>
		                                 </thead>
		                              </table>
		                  	</div>
		                  	<div class="col-lg-6 m-b-40">
		                  		<div id="id-chart-04" style="height: 420px"></div>
		                             <table id="id-table-04" class="table table-bordered content-center"  cellspacing="0" width="100%">
		                                 <thead>
		                                     <tr>
		                                         <th>&nbsp;</th>
		                                         <th>2023年</th>
		                                         <th>2024年</th>
		                                         <th>2025年</th>
		                                         <th>2026年</th>
		                                         <th>2027年</th>
		                                     </tr>
		                                 </thead>
		                              </table>
		                  	</div>
		                  </div>
                    </div>
				<table style="display:none;" id="id-table-05" class="table table-bordered content-center m-t-20"  cellspacing="0">
					<thead>
					<tr>
						<th colspan="8" id="tableTitle"></th>
					</tr>
					<tr>
						<th colspan="8" id="tableYear"></th>
					</tr>
					</thead>
					<thead>
					<tr>
						<th>姓名</th>
						<th>部门</th>
						<th>岗位</th>
						<th>单位</th>
						<th>ERP编号</th>
					</tr>
					</thead>
				</table>
                </div>
               	<!-- End PAge Content -->
            </div>
            <!-- End Container fluid  -->
</@panel.body>
<@panel.footer>
<script type="text/javascript" src="${ROOT}/mind/js/plugins/alangyun-filterbox.js"></script>
<script type="text/javascript" src="${ROOT}/mind/js/lib/datatables/datatables.min.js"></script>
<script type="text/javascript" src="${ROOT}/mind/js/lib/datatables/jquery.dataTables.zh-CN.js"></script>
<script type="text/javascript" src="${ROOT}/mind/js/lib/echart/echarts.min.5.4.0.js"></script>
<script type="text/javascript">
	// word导出事件
	document.getElementById('id-export-file').addEventListener('click', function() {
		// Ensure echarts charts have finished rendering
		setTimeout(() => {
			var charts = document.querySelectorAll('canvas');
			charts.forEach(chart => {
				var dataURL = chart.toDataURL();
				var imgTag = '<img src="' + dataURL + '" width="500" />';
				chart.insertAdjacentHTML('beforebegin', imgTag);
				chart.style.display = 'none'; // Hide the original canvas
			});

			// Create a temporary container for the export
			var exportContainer = document.createElement('div');
			exportContainer.id = 'export-container';
			exportContainer.style.width = '100%';

			// Clone ECharts charts
			var chartContainer = document.getElementById('id-chart-01').cloneNode(true);
			exportContainer.appendChild(chartContainer);

			var clonedTable = document.getElementById('id-table-01').cloneNode(true);
// 直接添加内联样式到每个th和td元素
			clonedTable.querySelectorAll('th, td').forEach(function(cell) {
				cell.style.border = '1px solid #000';
				cell.style.borderCollapse = 'collapse'; // 注意：borderCollapse是CSS属性，不能作为内联样式设置，但这里为了示例而写
				cell.style.textAlign = 'center';
			});
			exportContainer.appendChild(clonedTable);

			var chartContainer2 = document.getElementById('id-chart-02').cloneNode(true);
			exportContainer.appendChild(chartContainer2);
			var clonedTable2 = document.getElementById('id-table-02').cloneNode(true);
// 直接添加内联样式到每个th和td元素
			clonedTable.querySelectorAll('th, td').forEach(function(cell) {
				cell.style.border = '1px solid #000';
				cell.style.borderCollapse = 'collapse'; // 注意：borderCollapse是CSS属性，不能作为内联样式设置，但这里为了示例而写
				cell.style.textAlign = 'center';
			});
			exportContainer.appendChild(clonedTable2);

			var chartContainer3 = document.getElementById('id-chart-03').cloneNode(true);
			exportContainer.appendChild(chartContainer3);
			var clonedTable3 = document.getElementById('id-table-03').cloneNode(true);
// 直接添加内联样式到每个th和td元素
			clonedTable.querySelectorAll('th, td').forEach(function(cell) {
				cell.style.border = '1px solid #000';
				cell.style.borderCollapse = 'collapse'; // 注意：borderCollapse是CSS属性，不能作为内联样式设置，但这里为了示例而写
				cell.style.textAlign = 'center';
			});
			exportContainer.appendChild(clonedTable3);

			var chartContainer4 = document.getElementById('id-chart-04').cloneNode(true);
			exportContainer.appendChild(chartContainer4);
			var clonedTable4 = document.getElementById('id-table-04').cloneNode(true);
// 直接添加内联样式到每个th和td元素
			clonedTable.querySelectorAll('th, td').forEach(function(cell) {
				cell.style.border = '1px solid #000';
				cell.style.borderCollapse = 'collapse'; // 注意：borderCollapse是CSS属性，不能作为内联样式设置，但这里为了示例而写
				cell.style.textAlign = 'center';
			});
			exportContainer.appendChild(clonedTable4);

			// Convert the export container's HTML to a Word document
			var htmlHeader = `
          <!DOCTYPE html>
          <html>
          <head>
            <style>
               table, th, td {
                   border: 1px solid #000;
                   text-align: center;
                   border-collapse: collapse;
               }
            </style>
          </head>
          <body>`;
			var htmlFooter = `
          </body>
          </html>`;
			var htmlContent = htmlHeader + exportContainer.innerHTML + htmlFooter;

			var blob = new Blob([htmlContent], { type: 'application/msword' });
			var url = URL.createObjectURL(blob);
			var a = document.createElement('a');
			a.href = url;
			a.download = '职称等级晋升趋势.doc';
			a.click();
			URL.revokeObjectURL(url);

			// Clean up by removing the temporary container
			exportContainer.remove();

			// Revert changes made to the document for export
			charts.forEach(chart => {
				chart.previousSibling && chart.previousSibling.remove();
				chart.style.display = 'block'; // Restore the original canvas
			});
		}, 1000); // Adjust the timeout as needed to ensure charts have rendered
	});
$(document).ready(function(){
	
	$(".btn-click-bind").click(function() {
		  var val = $(this).data("sign");
		  var ctx = "/t/team";
		  if(12===val){
			  ctx = "/t/team12";
		  } else if(13===val){
			  ctx="/t/team13"
		  } else if(14===val){
			  ctx="/t/team14"
		  }
		  window.location.href="${ROOT}" + ctx;
	});
	

	

	//分析图
	var chartArray =[];
	chartArray.push( echarts.init(document.getElementById('id-chart-01'), null, {
      renderer: 'canvas',
      useDirtyRect: false
    }));
	chartArray.push(echarts.init(document.getElementById('id-chart-02'), null, {
        renderer: 'canvas',
        useDirtyRect: false
      }));
	chartArray.push(echarts.init(document.getElementById('id-chart-03'), null, {
        renderer: 'canvas',
        useDirtyRect: false
      }));
	chartArray.push(echarts.init(document.getElementById('id-chart-04'), null, {
        renderer: 'canvas',
        useDirtyRect: false
      }));

	var convertToChart = function(myChart, title, mydata){
		if(mydata==null)
			return;
		
		var labels = [];
		var counts = [];
		var trends = [];

		mydata.forEach(item => {
			labels.push(item.year+"年");
			counts.push(item.count);
			trends.push(item.trendCount);
		});
	
	    var option = {
		  tooltip: {
		    trigger: 'axis',
		    axisPointer: {
		      type: 'shadow'
		    }
		  },
		  title: {
			  text: title,
			  left: 'center'
		  },
		  xAxis: [
		    {
		      type: 'category',
		      data: labels
		    }
		  ],
		  yAxis: [
		    {
		      type: 'value'
		    }
		  ],
		  series: [
		    {
		      name: '具有资格人数',
		      type: 'bar',
		      emphasis: {
		        focus: 'series'
		      },
		      itemStyle: {
		    	  color: '#007470'
		      },
		      data: trends
		    },
		    {
		      name: '目标数 ',
		      type: 'line',
		      emphasis: {
		        focus: 'series'
		      },
		      itemStyle: {
		    	  color: '#00c4c0'
		      },
		      data: counts
		    }
		  ]
		};

	    if (option && typeof option === 'object') {
	      myChart.setOption(option);
	    }

	    window.addEventListener('resize', myChart.resize);
	}

	var tables = [null,null,null,null];   
	var elements = [$("#id-table-01"),$("#id-table-02"),$("#id-table-03"),$("#id-table-04")]
	var dataToTableView = function(index, mydata){
		if(!mydata || mydata.length==0)
			return;
		
		var columns = [];
		columns.push({
			'mData': 'name', 
			'caption': '&nbsp;',
			sWidth: '100px',
			defaultContent: '' 
		})
		var datas = [];
		var colIndex = 1;
		var value1 ={
				name: '具有资格人数'
		}
		var value2 = {
				name: '目标数'
		}
		mydata.forEach(item=>{

			var nm = 'col_'+ (colIndex++);
			columns.push({
				'mData': nm, 
				'caption': item.year+"年",
				'sTitle': item.year+"年",
				sWidth: '100px',
				defaultContent: '' 
			})
			value1[nm] = item.trendCount;
			value2[nm] = item.count;
			
		});
		datas.push(value1);
		datas.push(value2);
				
		var mytable = tables[index];
		if(mytable) {
			mytable.fnClearTable();
			mytable.fnDestroy();
		}
		
		mytable = elements[index].dataTable({
		    "ordering":false,
		    "searching": false,
		    "bFilter":false,
		    "info": false,
		    "paging": false,
		    'bAutoWidth':false,
		    "bDestroy" : true,
		    "aoColumns": columns,	
		    "data":datas
		});
		mytable.fnDraw();
		tables[index]= mytable;
		elements[index].off('click', 'td');
		elements[index].on('mouseenter', 'td', function() {
			// 获取当前行索引
			const rowIndex = $(this).parent().index();
			// 只有当行索引为0时，即第一行，才改变背景颜色
			if (rowIndex === 0) {
				$(this).css('background-color', '#e6f7ff');  // 浅蓝色背景
				$(this).css('cursor', 'pointer');  // 添加小手样式
			}
		}).on('mouseleave', 'td', function() {
			// 获取当前行索引
			const rowIndex = $(this).parent().index();
			// 只有当行索引为0时，即第一行，才恢复背景颜色
			if (rowIndex === 0) {
				$(this).css('background-color', '');  // 恢复原来的背景色
				$(this).css('cursor', '');  // 恢复默认的鼠标样式
			}
		});
		elements[index].on('click', 'td', function() {
			// 获取点击的单元格内容
			const cellValue = $(this).text().trim();

			// 获取点击的列索引
			const columnIndex = $(this).index();

			// 获取当前行索引
			const rowIndex = $(this).parent().index();

			// 只处理"具有资格人数"行的点击（第一行，索引为0）
			if (rowIndex === 0 && columnIndex > 0) {
				tableTitle = tableData[index].name
				// 获取对应的年份（从表头）
				yearData = elements[index].find('th').eq(columnIndex).text().replace('年','');

				document.getElementById('tableYear').innerHTML = yearData
				document.getElementById('tableTitle').innerHTML = tableTitle
				document.getElementById('id-table-05').style.display='inline-table'
				tableData[index].items.forEach((item,index)=>{
					if(item.year == yearData) {
						if(item.cautions) {
							dataToTableView1(item.cautions)
						} else {
							dataToTableView1([])
						}
					}
				})

				// 这里可以添加你的自定义处理逻辑
				// 例如：调用其他函数、显示详细信息等
			}
		});
	};
	var $table = null;
	var dataToTableView1 = function(mydata){
		if(!mydata){
			return;
		}

		if($table) {
			$table.fnClearTable();
			$table.fnDestroy();
		}

		$table = $("#id-table-05").dataTable({
			"ordering":false,
			"searching": false,
			"bFilter":false,
			"info": false,
			"paging": false,
			'bAutoWidth':false,
			"bDestroy" : true,
			"aoColumns": [
				{'mData': 'name', sWidth: '100px', defaultContent: '' },
				{'mData': 'departName', sWidth: '100px', defaultContent: '' },
				{'mData': 'job01Name', sWidth: '100px', defaultContent: '' },
				{'mData': 'unitName', sWidth: '100px', defaultContent: '' },
				{'mData': 'id', sWidth: '100px', defaultContent: '' },
			],
			"data":mydata
		});
		$table.fnDraw();
	};
    // 导出事件绑定
    // $('#id-export-file').click(function(){
    // 	var pdfCanvas = $.fn.pdfcanvas({
    // 		title: '人才队伍趋势预警 - 职称等级晋升趋势',
    // 		keywords: '单位和部门：；岗位类别：'
    // 	})
    // 	pdfCanvas.addDom(document.getElementById("id-diagram-group"));
    // 	pdfCanvas.print();
    //
    // });
	var tableData = []

    //初始化过滤面板
    $.post('${ROOT}/t/treeNav',function(data, status){
    	if(data.code==="ok"){
			$.fn.filterBox({
				data: data.data,
				onsubmit: function(form, data){
					var param = "tp=1";
					if(data){
						param = param +"&" + data;
					}
						
				    $.post('${ROOT}/t/trendSum',param,function(data, status){
				    	if(data && data.code === 'ok'){
				    		if(data.data && data.data.sums && data.data.sums.length >0){
				    			var index = 0;
				    			data.data.sums.forEach(sum=>{
									if(tableData.length>=4) {
										tableData = []
										tableData.push(sum)
									} else {
										tableData.push(sum)
									}
					    			convertToChart(chartArray[index], sum.name, sum.items);
						    		dataToTableView(index++, sum.items);
				    			})
				    		}
				    	}
				    }, 'json');
				}
			})
    	}
    });

	var tableTitle = ''
    //先提取数据
    $.post('${ROOT}/t/trendSum', 'tp=1',function(data, status){
    	if(data && data.code === 'ok'){
    		if(data.data && data.data.sums && data.data.sums.length >0){
    			var index = 0;
    			data.data.sums.forEach(sum=>{
					tableTitle = sum.name
					tableData.push(sum)
	    			convertToChart(chartArray[index], sum.name, sum.items);
		    		dataToTableView(index++, sum.items);
    			})
    		}
    	}
    }, 'json');
	
});
</script>
</@panel.footer>
</#escape>